import { defineComponent, onMounted, reactive, ref, watch, shallowRef } from 'vue'
import type { gqOptionsStateType, addOptionsPropsType, FormInfoMap } from './typings'
import {
  ElButton,
  ElDrawer,
  ElRow,
  ElCol,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElColorPicker,
  ElMessage
} from 'element-plus'
import type { FormInstance } from 'element-plus'
import InputTextarea from '~/components/ProForm/InputTextarea'
import { useStore } from 'vuex'
import styles from '../../index.module.scss'
import useVuexGetters from '~/hooks/useVuexGetters'
import amapIconRef from '~/assets/amapMarker.png'

export default defineComponent({
  name: 'EditShow',
  props: [
    // 值
    'visible',
    'type',
    'fullScreenBool',
    'record',
    'mapToolView',
    'overlaysArr',
    'buttonType', // 按钮类型
    'assetNameArr', // 所有列表数据
    'cancel',
    'getMapRandomPoint',
    'closeToolBtn',
    'editPolygon',
    'dynamicSurface',
    'activeFullScreen'
  ],
  setup(props: addOptionsPropsType, { expose }) {
    const getStoreData = useVuexGetters('assetWorkArea', ['polygonData', 'centerPoint'])
    const getStoreColorData = useVuexGetters('assetWorkArea', ['color'])

    const title = { add: '新增', update: '编辑' }
    const state = reactive<gqOptionsStateType>({
      activeTabKey: 'info'
    })
    const store = useStore()
    const getDom = ref() // 获取抽屉组件的dom元素
    // 颜色选择器的预定义颜色
    const predefineColors = ref([
      'rgba(255, 69, 0, 0.7)',
      'rgba(255, 140, 0, 0.6)',
      'rgba(255, 215, 0, 0.68)',
      'rgba(144, 238, 144, 0.62)',
      'rgba(0, 206, 209, 0.69)',
      'rgba(199, 21, 133, 0.64)',
      'rgba(79, 17, 160, 0.59)',
      'rgba(255, 120, 0, 1)',
      'rgba(107, 132, 28, 0.62)',
      'hsla(209, 100%, 56%, 0.73)'
    ])

    const ruleFormRef = ref<FormInstance>()
    const formInfoMap = reactive<FormInfoMap>(
      // 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。
      Object.assign(
        {
          name: '', // 名称
          width: 1, // 边线宽度
          backColor: 'rgba(192, 219, 246, 1)', // 默认背景色(浅蓝)
          bordeColor: 'rgba(7, 124, 254, 1)', // 默认边框色(蓝)
          areaTotal: 0, // 区域面积
          phase: '', // 空间点位
          sort: props.type === 'add' ? 1 : 0, // 排序，新增默认是1
          memo: '', // 备注
          id: '',
          centerPoint: ''
        },
        props.record
      )
    )

    watch(
      () => props.record!,
      () => {
        if (JSON.stringify(props.record) === '{}') {
          formInfoMap.name = '' // 名称
          formInfoMap.width = 1 // 边线宽度
          formInfoMap.backColor = 'rgba(192, 219, 246, 1)' // 默认背景色(浅蓝)
          formInfoMap.bordeColor = 'rgba(7, 124, 254, 1)' // 默认边框色(蓝)
          formInfoMap.areaTotal = 0 // 区域面积
          formInfoMap.phase = '' // 空间点位
          formInfoMap.sort = 1 // 排序，新增默认是1
          formInfoMap.memo = '' // 备注
          formInfoMap.id = ''
          formInfoMap.centerPoint = ''
        } else {
          Object.assign(formInfoMap, props.record) // 用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。
        }
        store.commit('assetWorkArea/SET_POLYGON_INFO', {
          id: props.record.id
        })
      }
    )

    // 新增/编辑时, 地图上实时更新面的属性
    watch(
      () => [formInfoMap.backColor, formInfoMap.bordeColor, formInfoMap.width],
      () => {
        const params = { ...formInfoMap }
        props.dynamicSurface!(params)
        store.commit('assetWorkArea/SET_COLOR_INFO', {
          id: props.record.id,
          fillColor: formInfoMap.backColor, // 填充色
          strokeColor: formInfoMap.bordeColor, // 边线颜色
          strokeWeight: formInfoMap.width // 线宽
        })
      }
    )

    onMounted(() => {
      // if (props.record?.id) {
      // 获取从主页面传过来的props参数，例如record
      // 修改操作，则鼠标穿透
      getDom.value.drawerRef.parentNode.className = styles.modelClass // 给抽屉组件的父容器添加样式
      // }

      // 设置默认值给vuex
      store.commit('assetWorkArea/SET_COLOR_INFO', {
        id: props.record.id,
        fillColor: formInfoMap.backColor, // 填充色
        strokeColor: formInfoMap.bordeColor, // 边线颜色
        strokeWeight: formInfoMap.width // 线宽
      })
    })

    // 取消
    const handleCancel = () => {
      props.closeToolBtn!() // 提交前先关工具条操作
      props.cancel()
      // getStoreData.polygonData.value.polyArr = ''
      // getStoreData.polygonData.value.id = ''
      // getStoreData.polygonData.value.areaTotal = 0
    }

    // 填充颜色
    const fillChange = (value: string) => {
      formInfoMap.backColor = value // 填充颜色
    }

    // 边线颜色
    const lineChange = (value: string) => {
      formInfoMap.bordeColor = value // 边线颜色
    }

    // 边线宽度
    const numInput = (currentValue: number) => {
      formInfoMap.width = currentValue // 边线宽度
    }

    // 保存提交表单
    const handleSubmitForm = async (noClose?: boolean) => {
      // 关闭工具条操作后才能提交
      // if (props.buttonType.buttonType !== undefined) {
      //   ElMessage({ type: 'warning', message: '请先保存图形再离开' })
      //   return
      // }

      // 同一个租户下区域名称唯一
      const beforeName = props.record.name ?? ''
      if (props.assetNameArr) {
        for (let i = 0; i < props.assetNameArr.length; i++) {
          if (props.assetNameArr[i].name === formInfoMap.name && formInfoMap.name !== beforeName) {
            ElMessage({ type: 'warning', message: '已存在同一区域名称的数据' })
            return
          }
        }
      }
      if (!ruleFormRef.value) return
      await ruleFormRef.value.validate(async (valid: boolean) => {
        if (!valid) return
        props.closeToolBtn!() // 提交前先关工具条操作

        // 编辑空间和属性信息
        formInfoMap.phase =
          (getStoreData.polygonData.value.polyArr
            ? getStoreData.polygonData.value.polyArr
            : formInfoMap.phase) || undefined

        // 面积
        formInfoMap.areaTotal =
          (getStoreData.polygonData.value.areaTotal
            ? getStoreData.polygonData.value.areaTotal
            : formInfoMap.areaTotal) || undefined

        const params = { ...formInfoMap }
        // 获取当前修改图案上的文本点（新增的需要重新生成，因为可能点不准确）
        // if (formInfoMap.phase) {
        //   if (props.record?.id) {
        //     const editAreaPolygon = props.overlaysArr.find(
        //       (item: addOptionsPropsType['record']) => item?.id === props.record?.id
        //     )
        //     params.centerPoint = JSON.stringify(editAreaPolygon.text?.getPosition?.()?.toArray())
        //   } else {
        //     params.centerPoint = JSON.stringify(
        //       getStoreData.polygonData.value?.polygonType !== 'MultiPolygon'
        //         ? props.getMapRandomPoint!(
        //             getStoreData.polygonData.value?.polygonPath[0],
        //             getStoreData.polygonData.value?.polygonPath
        //           )
        //         : props.getMapRandomPoint!(
        //             getStoreData.polygonData.value?.polygonPath[0][0],
        //             getStoreData.polygonData.value?.polygonPath[0]
        //           )
        //     )
        //   }
        // }

        // 接口调用
        const res = await store.dispatch(
          props.type === 'add' ? 'assetWorkArea/AddWorkArea' : 'assetWorkArea/UpdateWorkArea',
          params
        )
        if (res?.code === 200) {
          ElMessage({ type: 'success', message: '操作成功' })
          // if (!noClose) props.cancel(params)
          if (!noClose) props.cancel({})
          getStoreColorData.color.value.fillColor = ''
          getStoreColorData.color.value.strokeColor = ''
          getStoreColorData.color.value.strokeWeight = ''
          //  移除点击事件
          props.mapToolView.mapRef.off('click')
          if (marker.value) {
            marker.value.setMap(null)
            marker.value = null
          }
        }
      })
    }

    //  取点
    const marker = shallowRef()
    const onPickingPoints = () => {
      props.mapToolView.mapRef.on('click', (e: any) => {
        if (marker.value) {
          marker.value.setMap(null)
          marker.value = null
        }
        const { lng, lat } = e.lnglat
        const point = [lng, lat]
        formInfoMap.centerPoint = JSON.stringify(point)

        const icon = new props.mapToolView.aMapRef.Icon({
          size: new props.mapToolView.aMapRef.Size(28, 28),
          imageSize: new props.mapToolView.aMapRef.Size(28, 28),
          image: amapIconRef
        })
        marker.value = new props.mapToolView.aMapRef.Marker({
          icon,
          position: point,
          offset: [-13, -30]
        })
        marker.value.setMap(props.mapToolView.mapRef)
      })
    }

    expose({ submitAreaForm: handleSubmitForm })

    return () => (
      <ElDrawer
        ref={getDom}
        title={(title[props.type!] as string) || '查看'}
        modelValue={props.visible && !props.activeFullScreen}
        appendToBody={false}
        beforeClose={() => handleCancel()}
        customClass={styles['form-elDrawer']}
        size={372}
        modal={false}
        v-slots={
          (state.activeTabKey === 'info' || state.activeTabKey === 'mapLocation') && {
            footer: () => (
              <>
                <ElButton class={styles.elButtonDraw} onClick={() => handleCancel()}>
                  取消
                </ElButton>
                <ElButton
                  type="primary"
                  class={styles.elButtonDraw}
                  onClick={() => handleSubmitForm()}
                >
                  {props.type === 'add' ? '保存' : '修改'}
                </ElButton>
              </>
            )
          }
        }
      >
        <ElForm labelWidth="100px" model={formInfoMap} ref={ruleFormRef} labelPosition="right">
          <ElRow class={styles['form-elRow']}>
            <ElCol>
              <ElFormItem
                prop="name"
                label="区域名称"
                class={styles['form-elInput']}
                rules={[
                  { required: true, whitespace: true, message: '请输入区域名称' },
                  { min: 2, whitespace: true, message: '区域名称长度为2～20字符' }
                ]}
              >
                <ElInput
                  v-model={formInfoMap.name}
                  {...{ minlength: 2, maxlength: 20 }}
                  clearable={true}
                  style="height:32px"
                />
              </ElFormItem>
            </ElCol>
            <ElCol>
              <ElFormItem
                class={styles['form-elInput']}
                prop="backColor"
                label="背景颜色"
                style="height:32px"
              >
                <ElColorPicker
                  onActive-change={fillChange}
                  v-model={formInfoMap.backColor}
                  showAlpha
                  // show-alpha
                  predefine={predefineColors.value}
                />
              </ElFormItem>
            </ElCol>
            <ElCol>
              <ElFormItem
                prop="bordeColor"
                label="边框颜色"
                class={styles['form-elInput']}
                rules={[{ required: false, message: '边框颜色' }]}
              >
                <ElColorPicker
                  onActive-change={lineChange}
                  v-model={formInfoMap.bordeColor}
                  showAlpha
                  // show-alpha
                  predefine={predefineColors.value}
                />
              </ElFormItem>
            </ElCol>
            <ElCol>
              <ElFormItem
                prop="width"
                class={styles['form-elInput']}
                label="边框宽度"
                rules={[{ required: false, message: '请输入边框宽度' }]}
              >
                <ElInputNumber
                  v-model={formInfoMap.width}
                  min={1}
                  max={10}
                  size="large"
                  onChange={(currentValue) => numInput(currentValue!)}
                  controls-position="right"
                />
              </ElFormItem>
            </ElCol>
            <ElCol>
              <ElFormItem
                prop="memo"
                label="备注"
                class={styles['form-elInput']}
                rules={[{ required: false, message: '请输入备注' }]}
              >
                {/* <ElInput
                  type="textarea"
                  // v-model={inputTextareaValue}
                  v-model={formInfoMap.memo}
                  placeholder="请输入"
                  clearable
                  {...{ maxlength: 100 }}
                  showWordLimit
                /> */}
                <InputTextarea
                  v-model:inputTextareaValue={formInfoMap.memo}
                  placeholderName="请输入"
                  limitLength={100}
                />
              </ElFormItem>
            </ElCol>
            <ElCol>
              <ElFormItem
                prop="centerPoint"
                label="修正中心点"
                class={styles['form-elInput']}
                rules={[{ required: true, message: '请输入修正中心点' }]}
              >
                <ElInput
                  v-model={formInfoMap.centerPoint}
                  {...{ minlength: 2, maxlength: 20 }}
                  clearable={true}
                  style="width: 150px;"
                />
                &nbsp; &nbsp;
                <ElButton type="primary" onClick={onPickingPoints}>
                  取点
                </ElButton>
              </ElFormItem>
            </ElCol>
          </ElRow>
        </ElForm>
      </ElDrawer>
    )
  }
})
